// pages/baike/bk.js

const app = getApp()
const pool = new Map()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        current: 0,
        list: []
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        pool.clear()
        this.loadCategory()
    },
    loadCategory() {
        app.http.get('shop-article/all-category', {
            data: {}
        }).then(res => {
            if (res.data.length > 0) {
                this.setData({
                    categoryList: [{ id: 0, name: "全部" }].concat(res.data),
                });
                this.loadData();
            }
        }).catch(err => {
            app.wxToast.error(err.message);
        })
    },

    loadData() {
        let tab = pool.get(this.data.current)
        if (!tab) {
            tab = { page: 1, total: 2, list: [] }
            pool.set(this.data.current, tab)
        }
        if (tab.page > tab.total || this.data.loading) {
            this.setData(tab)
            return
        }
        wx.showLoading({
            title: '加载中...',
        })
        this.setData({
            loading: true
        })

        app.http.get("shop-article/index", {
            data: { cid: this.data.categoryList[this.data.current].id, page: tab.page }
        }).then(res => {
            tab.list.push.apply(tab.list, res.data.items)
            tab.page++
            tab.total = res.data.total
            this.setData(tab)
            wx.hideLoading()
            wx.stopPullDownRefresh()
            this.setData({
                loading: false
            })
        }).catch(err => {
            app.wxToast.error(err.message)
            this.setData({
                loading: false
            })
        })
    },

    typeClick(evt) {
        const current = evt.currentTarget.dataset.current
        if (this.data.current != current) {
            this.setData({
                current
            })
            this.loadData()
        }
    },
    onSwiper(evt) {
        setTimeout(() => {
            this.setData({
                current: evt.detail.current
            })
        }, 10)
    },
    onReachBottom() {
        this.loadData()
    },
    onPullDownRefresh() {
        pool.delete(this.data.current)
        this.loadData()
    },
    onShareAppMessage: function () {
        return app.getShareObj('邀请你来逛逛' + wx.getStorageSync('store'))
    }
})

